<template>
  <div>
<div class="filter-container">
      <el-input
        v-model="listQuery.username"
        placeholder="用户名称"
        style="width: 200px"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <span style="margin-left: 20px" />
      <el-button
        class="filter-item"
        type=""
        icon="el-icon-search"
        @click="handleFilter"
      >
        筛选
      </el-button>
      <el-button class="filter-item" type="danger" icon="el-icon-delete">
        删除
      </el-button>
      <el-button
        class="filter-item"
        style="float: right"
        type="primary"
        icon="el-icon-edit"
        @click="handleShowUserForm('adminAdd')"
      >
        添加
      </el-button>
    </div>
    <br />
  <el-table
      key="user"
      v-loading="listLoading"
      :data="userList"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column
        type="selection"
        width="55"
        label="ID"
        align="center"
        prop="id"
      />
      <el-table-column label="图片" align="center">
        <template slot-scope="{ row }">
          <img width="60px" height="60px" :src="row.head_img" />
        </template>
      </el-table-column>
      <el-table-column label="用户名" align="center" prop="username"/>
      <el-table-column label="昵称" align="center" prop="nickname" />
      <el-table-column label="手机号" align="center" prop="mobile" />
      <el-table-column label="登录次数" align="center" prop="login_num" />
      <el-table-column label="状态" align="center">
        <template slot-scope="{ row }">
          <el-switch
            v-model="row.status"
            @change="switchChange(row)"
            name="status"
            :active-value="1"
            :inactive-value="0"
          />
        </template>
      </el-table-column>
      <el-table-column label="添加时间" align="center" prop="created_at" />
      <el-table-column label="操作" align="center">
        <template slot-scope="{ row }">
          <el-button-group>
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="handleShowUserForm('adminEdit', row)"
            />
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="handleDeleteUser(row)"
            />
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.size"
      @pagination="getList"
    />

    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      width="50%"
      :append-to-body="true"
      @close="handleUserFormClose"
    >
      <el-form
        v-loading="getInfoLoading"
        ref="userFormRef"
        :rules="rules"
        :model="formDefaultValue"
        label-position="right"
        label-width="100px"
        style="margin-left: 30px; margin-right: 30px"
      >
            <el-form-item label="用户权限" prop="relo_ids">
              <el-checkbox-group v-model="formDefaultValue.role_ids">
                <el-checkbox v-for="(role,roleIndex) in roleList" :label="role.id.toString()" :key="roleIndex">{{role.title}}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="用户名称" prop="username">
              <el-input v-model="formDefaultValue.username" />
            </el-form-item>
            <el-form-item label="用户昵称" prop="nickname">
              <el-input v-model="formDefaultValue.nickname" />
            </el-form-item>
            <el-form-item label="用户密码" prop="password">
              <el-input type="password" v-model="formDefaultValue.password" />
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
              <el-input v-model="formDefaultValue.mobile" />
            </el-form-item>
            <el-form-item label="图片">
              <zz-imgbox v-model="formDefaultValue.head_img" v-cloak></zz-imgbox>
            </el-form-item>
            <el-form-item label="状态">
              <el-radio-group v-model="formDefaultValue.status">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" v-model="formDefaultValue.remark" />
            </el-form-item>
            <el-form-item label="排序" prop="sort">
              <el-input v-model="formDefaultValue.sort" />
            </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false"> 取消 </el-button>
        <el-button type="primary" @click="submitUserForm"> 确认 </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import ApiSetting from "@/api/setting"
export default {
  name: "Users",
  data() {
    return {
      userList: [],
      total: 0,
      listLoading: false,
      getInfoLoading: false,
      listQuery: {
        page: 1,
        size: 20,
        username: undefined
      },
      dialogStatus: "",
      textMap: {
        adminEdit: "编辑用户",
        adminAdd: "添加用户",
      },
      formDefaultValue: {
        id: undefined,
        role_ids:[],
        head_img:'',
        username:'',
        password:'',
        nickname:'',
        mobile:'',
        remark:'',
        sort:'99',
        status:1,
      }, // 表单默认值
      roleList:[],
      rules: {
        username: [
          { required: true, message: "username is required", trigger: "blur" },
        ],
      }, // 验证规则
      dialogFormVisible:false
    };
  },
  created() {
    // 获取用户列表
    this.getList();
  },
  methods: {
    // 获取用户列表
    getList() {
      let _this = this;
      this.listLoading = true;
      ApiSetting
        .adminList(_this.listQuery)
        .then((res) => {
          if (res.errCode == 0) {
            _this.userList = res.data.list;
            _this.total = res.data.total;
          } else {
            _this.$message(res.errMsg);
          }

          _this.listLoading = false;
        })
        .catch((err) => {
          _this.listLoading = false;
          console.log(err);
        });
    },

    // 筛选用户列表
    handleFilter() {
      this.listQuery.page = 1; //请求页重置为1
      this.getList();
    },

    // 用户表单弹出处理
    handleShowUserForm(action = undefined, user = {}) {
      this.dialogStatus = action;
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["userFormRef"].clearValidate();
      });
      const _this = this;
      if (action == "adminEdit" && user.id != undefined) {
        this.getInfoLoading = true;
        ApiSetting
          .adminInfo(user.id)
          .then((res) => {
            _this.formDefaultValue = res.data;
            _this.getInfoLoading = false;
          })
          .catch((err) => {
            console.log(err);
          });
      }
      this.getRoles() // 获取角色列表
    },

    /**
     * 获取角色列表
     */
    getRoles(){
      let _this = this;
      ApiSetting
        .systemAuthList({size:1000})
        .then((res) => {
          if (res.errCode == 0) {
            _this.roleList =res.data.list
          } else {
            _this.$message(res.errMsg);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },

    // 关闭表单处理
    handleUserFormClose() {
      this.$refs.userFormRef.resetFields(); //重置表单值
      Object.assign(this.$data.formDefaultValue, this.$options.data().formDefaultValue);
    },

    // 设置用户状态
    switchChange(row) {
      // ApiSetting
      //   .setStatus({ ids: [row.id], status: row.status })
      //   .then((res) => {
      //     this.$message({ message: res.msg, type: "success" });
      //   });
    },

    // 删除用户处理
    handleDeleteUser(row) {
      this.$confirm("删除用户,", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          ApiSetting
            .deleteUser({ ids: [row.id], is_delete: 1 })
            .then((res) => {
              if (res.code == 1) {
                this.getList();
                this.$message({
                  type: "success",
                  message: res.msg,
                });
              }
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    /**
     * 提交表单
     */
    submitUserForm() {
      const _this = this;
      let action = _this.dialogStatus;
      this.$refs.userFormRef.validate((valid) => {
        if (valid) {
          ApiSetting[action](_this.formDefaultValue)
            .then((res) => {
              console.log(res);
              if (res.errCode === 0) {
                _this.getList();
              } else {
                _this.$message.error("操作" + res.errMsg);
              }
              _this.dialogFormVisible = false;
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
          _this.$message("操作失败");
          return false;
        }
      });
    },
  },
};
</script>

<style>
</style>
